package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginContorller {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JSONResult login(String username, String password){

        try {

            Employee employee = employeeService.login(username,password);
            //把当前登录用户存到session中
            //session.setAttribute(UserContext.USER_IN_SESSION, employee);
            UserContext.setCurrentUser(employee);
            //判断是否超级管理员,如果不是就查询
            if (!employee.isAdmin()){

                //根据登录用户id查询该员工拥有的权限表达式列表,存到session中

                List<String> expression = permissionService.selectExpressionByEmpId(employee.getId());
                //session.setAttribute(UserContext.EXPRESSION_IN_SESSION, expression);
                UserContext.setExpression(expression);
            }

            return new JSONResult();
        } catch(Exception e) {
            e.printStackTrace();

            return new JSONResult(false,e.getMessage());
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){

        session.invalidate();  //销毁会话
        return "redirect:/login.html";
    }
}
